package com.basic.technology.study.introduction.exception;

/**
 * @Description
 * 该程序在一个try块中嵌套了另一个try块。程序工作如下：当你在没有命令行参数的情况下执行该程序，外面的try块将产生一个被零除的异常。程序在有一个命令行参数条件下执行，由嵌套的try块产生一个被零除的错误。因为内部的块不匹配这个异常，它将把异常传给外部的try块，在那里异常被处理。如果你在具有两个命令行参数的条件下执行该程序，由内部try块产生一个数组边界异常。下面的结果阐述了每一种情况：
 * Divide by 0: java.lang.ArithmeticException: / by zero
 * a = 1
 * Divide by 0: java.lang.ArithmeticException: / by zero
 * a = 2
 * Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException
 *
 * @Author 程杰
 * @Date 2020/11/6 15:58
 * @Version 1.0
 */
public class ExceptionDemo3 {
    public static void main(String[] args) {
        try {
            int a = args.length;
            a=1;
            /* If no command-line args are present,the following statement will generate a divide-by-zero exception. */
            int b = 42 / a;
            System.out.println("a = " + a);
            try { // nested try block
                /* If one command-line arg is used,then a divide-by-zero exception will be generated by the following code. */
                if(a==1) {
                    // division by zero
                    a = a/(a-a);
                }
                /* If two command-line args are used,then generate an out-of-bounds exception. */
                if(a==2) {
                    int[] c = { 1 };
                    // generate an out-of-bounds exception
                    c[42] = 99;
                }
            } catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("Array index out-of-bounds: " + e);
            }
        } catch(ArithmeticException e) {
            System.out.println("Divide by 0: " + e);
        }
    }
}
